//
//  CandyTableViewController.swift
//  CandySearch
//
//  Created by cygarm on 15/7/26.
//  Copyright (c) 2015年 cygarm. All rights reserved.
//

import UIKit

/*
UISearchBarDelegate defines the behavior and response of a search, while UISearchDisplayDelegate defines the look and feel of the search bar.
*/
class CandyTableViewController: UITableViewController, UISearchBarDelegate, UISearchResultsUpdating {
  
    var candies = [Candy]()
    var filteredCandies = [Candy]()
    var resultSearchController = UISearchController()
    var selectedScope = "All"

    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
      
        // Sample Data for candyArray
        self.candies = [Candy(category:"Chocolate", name:"chocolate Bar"),
        Candy(category:"Chocolate", name:"chocolate Chip"),
        Candy(category:"Chocolate", name:"dark chocolate"),
        Candy(category:"Hard", name:"lollipop"),
        Candy(category:"Hard", name:"candy cane"),
        Candy(category:"Hard", name:"jaw breaker"),
        Candy(category:"Other", name:"caramel"),
        Candy(category:"Other", name:"sour chew"),
        Candy(category:"Other", name:"gummi bear")]

        self.resultSearchController = ({
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.dimsBackgroundDuringPresentation = false
            controller.searchBar.sizeToFit()
            controller.searchBar.scopeButtonTitles = ["All", "Chocolate", "Hard", "Other"]
            controller.searchBar.delegate = self
            
            self.tableView.tableHeaderView = controller.searchBar
            
            return controller
        })()


        //Reload the table
        self.tableView.reloadData()
    }
    
/*
    UISearchBar Delegate 会自动处理更新.active状态
*/
//    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//        if segue.identifier == "DetailSegue" {
//            let controller = segue.destinationViewController as! UIViewController
//            
//            if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell) {
//                controller.title = candies[indexPath.row].name
//            }
//            
//            if (self.resultSearchController.active) {
//                self.resultSearchController.active = false
//            }
//        }
//    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
      
      if self.resultSearchController.active {
        return self.filteredCandies.count
      } else {
        return self.candies.count
      }
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
      
        var candy:Candy
        // Check to see whether the normal table or search results table is being displayed and set the Candy object from the appropriate array
        if self.resultSearchController.active {
          candy = filteredCandies[indexPath.row]
        } else {
          candy = candies[indexPath.row]
        }
      
        // configure the cell
        cell.textLabel!.text = candy.name
        cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator

        return cell
    }
    
    // MARK: - Helpers methods
    func filterContentForSearchText(searchText: String, scope: String = "All") {
        // Filter the array using the filter method
        self.filteredCandies = self.candies.filter({(candy: Candy) -> Bool in
            let categoryMatch = (scope == "All") || (candy.category == scope)
            let stringMatch = candy.name.rangeOfString(searchText)
            
            return categoryMatch && (stringMatch != nil)
        })
    }
  
    // MARK: - UISearchControllerDelegate
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        filteredCandies.removeAll(keepCapacity: false)
        filterContentForSearchText(searchController.searchBar.text, scope: selectedScope)
        tableView.reloadData()
    }

    // MARK: - UISearchBarDelegate
    func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
        switch selectedScope {
        case 0:
            self.selectedScope = "All"
            break
        case 1:
            self.selectedScope = "Chocolate"
            break
        case 2:
            self.selectedScope = "Hard"
            break
        case 3:
            self.selectedScope = "Other"
            break
        default:
            self.selectedScope = "All"
            break
        }
    }
}
